package com.exercise.common;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

 /**
 * 全局异常处理
 * @author 陈凯
 * @create 2023-03-06-15:46
 */

@ControllerAdvice(annotations = {RestController.class})
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException e){

        if (e.getMessage().contains("Duplicate entry")){
            String[] split = e.getMessage().split(" ");
            String msg = split[2] + "已存在，请重新输入";
            return R.error(msg);
        }

        return R.error("未知错误");
    }

    @ExceptionHandler(ServiceException.class)
    public R<String> exceptionHandler(ServiceException e){
        return R.error(e.getMessage());
    }
}
